#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <cmath>

#include "Shader.h"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

// 窗口大小变化回调函数
void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
    glViewport(0, 0, width, height);
}

// 输入处理
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// 打印使用说明
void printUsage()
{
    std::cout << "按下数字键切换不同演示效果:" << std::endl;
    std::cout << "1 - 标准透视投影 (FoV=45, aspect=800/600)" << std::endl;
    std::cout << "2 - 更大FoV (FoV=90, aspect=800/600)" << std::endl;
    std::cout << "3 - 更小FoV (FoV=22.5, aspect=800/600)" << std::endl;
    std::cout << "4 - 更宽的宽高比 (FoV=45, aspect=2*800/600)" << std::endl;
    std::cout << "5 - 更窄的宽高比 (FoV=45, aspect=0.5*800/600)" << std::endl;
    std::cout << "ESC - 退出程序" << std::endl;
}

int main()
{
    printUsage();

    /**
     * 实例化GLFW窗口
     */
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /**
     * 创建窗口对象
     */
    GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Projection Demo", nullptr, nullptr);
    if (window == nullptr)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }

    // 设置OpenGL上下文
    glfwMakeContextCurrent(window);

    /**
     * 初始化GLAD
     */
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // 使用着色器文件创建着色器程序
    Shader ourShader("../data/4_MoreCubic.vs", "../data/coordinate_systems.fs");

    // 创建顶点数组对象
    unsigned int VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    // 创建顶点缓冲对象
    unsigned int VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    /**
     * 顶点输入 - 创建一个大立方体用于演示
     */
    float vertices[] = {
        // 前面
        -0.5f, -0.5f,  0.5f, 0.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 0.0f, 0.0f,

        // 后面
        -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,

        // 左面
        -0.5f,  0.5f,  0.5f, 1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 0.0f,

        // 右面
         0.5f,  0.5f,  0.5f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 0.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 0.0f,

        // 上面
        -0.5f,  0.5f, -0.5f, 0.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 0.0f, 1.0f,

        // 下面
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f, 0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f
    };

    // 把顶点数据复制到缓冲的内存中
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // 设置顶点属性指针
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    // 生成纹理
    unsigned int texture1;
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1);
    // 纹理环绕方式
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // 纹理过滤
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // 加载并生成纹理
    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(true);
    unsigned char *data = stbi_load("../data/container.jpg", &width, &height, &nrChannels, 0);
    if (data)
    {
        GLenum format = GL_RGB;
        if (nrChannels == 1)
            format = GL_RED;
        else if (nrChannels == 3)
            format = GL_RGB;
        else if (nrChannels == 4)
            format = GL_RGBA;

        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);

    // 注册窗口大小变化回调函数
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // 使用着色器程序
    ourShader.use();
    ourShader.setInt("texture1", 0);

    glEnable(GL_DEPTH_TEST);

    // 当前演示模式
    int demoMode = 1;
    bool keyProcessed[10] = {false};

    /**
     * 渲染循环
     */
    while (!glfwWindowShouldClose(window))
    {
        processInput(window);

        // 处理键盘输入
        if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS && !keyProcessed[1]) {
            demoMode = 1;
            keyProcessed[1] = true;
            std::cout << "切换到演示模式 1: 标准透视投影 (FoV=45, aspect=800/600)" << std::endl;
        }
        if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS && !keyProcessed[2]) {
            demoMode = 2;
            keyProcessed[2] = true;
            std::cout << "切换到演示模式 2: 更大FoV (FoV=90, aspect=800/600)" << std::endl;
        }
        if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS && !keyProcessed[3]) {
            demoMode = 3;
            keyProcessed[3] = true;
            std::cout << "切换到演示模式 3: 更小FoV (FoV=22.5, aspect=800/600)" << std::endl;
        }
        if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS && !keyProcessed[4]) {
            demoMode = 4;
            keyProcessed[4] = true;
            std::cout << "切换到演示模式 4: 更宽的宽高比 (FoV=45, aspect=2*800/600)" << std::endl;
        }
        if (glfwGetKey(window, GLFW_KEY_5) == GLFW_PRESS && !keyProcessed[5]) {
            demoMode = 5;
            keyProcessed[5] = true;
            std::cout << "切换到演示模式 5: 更窄的宽高比 (FoV=45, aspect=0.5*800/600)" << std::endl;
        }

        // 释放按键状态
        for (int i = 1; i <= 5; i++) {
            if (glfwGetKey(window, GLFW_KEY_0 + i) == GLFW_RELEASE) {
                keyProcessed[i] = false;
            }
        }

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // 使用着色器程序
        ourShader.use();

        // 创建视图矩阵
        glm::mat4 view = glm::mat4(1.0f);
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));

        // 根据演示模式创建不同的投影矩阵
        glm::mat4 projection = glm::mat4(1.0f);
        switch (demoMode) {
            case 1: // 标准透视投影
                projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
                break;
            case 2: // 更大FoV
                projection = glm::perspective(glm::radians(90.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
                break;
            case 3: // 更小FoV
                projection = glm::perspective(glm::radians(22.5f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
                break;
            case 4: // 更宽的宽高比
                projection = glm::perspective(glm::radians(45.0f), 2.0f * (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
                break;
            case 5: // 更窄的宽高比
                projection = glm::perspective(glm::radians(45.0f), 0.5f * (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
                break;
        }

        // 创建模型矩阵 - 让立方体缓慢旋转
        glm::mat4 model = glm::mat4(1.0f);
        model = glm::rotate(model, (float)glfwGetTime() * glm::radians(50.0f), glm::vec3(0.5f, 1.0f, 0.0f));

        // 传递矩阵给着色器
        ourShader.setMat4("model", model);
        ourShader.setMat4("view", view);
        ourShader.setMat4("projection", projection);

        // 绑定纹理并绘制
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);

        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // 删除缓冲对象和顶点数组对象
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    // 释放资源
    glfwTerminate();

    return 0;
}